package com.zhao.fishingguideserver.controller;

import com.zhao.fishingguideserver.POJO.Order;
import com.zhao.fishingguideserver.POJO.Result;
import com.zhao.fishingguideserver.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理端订单管理控制器
 */
@RestController
@RequestMapping("/admin/order")
public class AdminOrderController {
    
    @Autowired
    private OrderMapper orderMapper;
    
    /**
     * 获取订单列表
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> getOrderList(@RequestParam(required = false) String status,
                                                    @RequestParam(required = false) Integer page,
                                                    @RequestParam(required = false) Integer pageSize) {
        try {
            int safePage = (page == null || page < 1) ? 1 : page;
            int safePageSize = (pageSize == null || pageSize < 1 || pageSize > 100) ? 10 : pageSize;
            int offset = (safePage - 1) * safePageSize;
            
            int total = orderMapper.countOrders(status);
            List<Order> list = orderMapper.selectOrdersPaged(status, offset, safePageSize);
            
            Map<String, Object> data = new HashMap<>();
            data.put("list", list);
            data.put("total", total);
            data.put("page", safePage);
            data.put("pageSize", safePageSize);
            return Result.success(data);
        } catch (Exception e) {
            return Result.error("获取订单列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取订单详情
     */
    @GetMapping("/detail/{id}")
    public Result<Order> getOrderDetail(@PathVariable Integer id) {
        try {
            Order order = orderMapper.selectById(id);
            if (order == null) {
                return Result.error("订单不存在");
            }
            return Result.success(order);
        } catch (Exception e) {
            return Result.error("获取订单详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取订单统计数据
     */
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getOrderStatistics() {
        try {
            Map<String, Object> stats = new HashMap<>();
            List<Order> orders = orderMapper.selectAll();
            
            // 统计各状态订单数量
            long pendingCount = orders.stream().filter(o -> "pending".equals(o.getStatus())).count();
            long paidCount = orders.stream().filter(o -> "paid".equals(o.getStatus())).count();
            long shippedCount = orders.stream().filter(o -> "shipped".equals(o.getStatus())).count();
            long deliveredCount = orders.stream().filter(o -> "delivered".equals(o.getStatus())).count();
            long cancelledCount = orders.stream().filter(o -> "cancelled".equals(o.getStatus())).count();
            
            stats.put("totalOrders", orders.size());
            stats.put("pendingCount", pendingCount);
            stats.put("paidCount", paidCount);
            stats.put("shippedCount", shippedCount);
            stats.put("deliveredCount", deliveredCount);
            stats.put("cancelledCount", cancelledCount);
            
            // 计算总交易额（已支付、已发货、已收货的订单）
            double totalAmount = orders.stream()
                .filter(o -> "paid".equals(o.getStatus()) || 
                           "shipped".equals(o.getStatus()) || 
                           "delivered".equals(o.getStatus()))
                .mapToDouble(o -> o.getTotalAmount() != null ? o.getTotalAmount().doubleValue() : 0)
                .sum();
            stats.put("totalAmount", totalAmount);
            
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error("获取订单统计失败：" + e.getMessage());
        }
    }
}

